{extend name='public/base'/}
{block name='meta'}{/block} {//关掉mata}
{block name='seo'}
<title>{$title|default="课程创建"}</title>
<meta name="keywords" content="{$keywords|default='关键字'}">
<meta name="description" content="{$desc|default='描述'}">


<link rel="stylesheet" href="__STATIC__/lib/chess/chess.css" />


{/block}

{block name='content'}
<section class="Hui-article-box">
	<nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 首页
		<span class="c-gray en">&gt;</span>
		课程管理
		<span class="c-gray en">&gt;</span>
		单步课程创建 <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新" ><i class="Hui-iconfont">&#xe68f;</i></a>
	</nav>
</section>

	<div class="Hui-article mt-40">
    <article class="cl pd-20">
	<form action="{:url('course/saveChess')}" method="post" class="form form-horizontal" id="form-teacher-edit">
		<div id="container">
			<article style="float: left;margin-right: 60px;">
				<section>
					<svg id="chessboard" width="600" height="600" style="background: GoldenRod">
						<defs>
							<radialGradient id="rgBlack" cx="25%" cy="25%" r="50%" fx="25%" fy="25%">
								<stop offset="0%" style="stop-color:rgb(200,200,200);stop-opacity:1" />
								<stop offset="100%" style="stop-color:rgb(0,0,0);stop-opacity:1" />
							</radialGradient>
							<radialGradient id="rgWhite" cx="25%" cy="25%" r="50%" fx="25%" fy="25%">
								<stop offset="0%" style="stop-color:rgb(255,255,255);stop-opacity:1" />
								<stop offset="100%" style="stop-color:rgb(200,200,200);stop-opacity:1" />
							</radialGradient>
						</defs>
					</svg>
				</section>
			</article>

			<aside>
				<section>
					<p class="text-warning" style="font-size: 16px; font-weight: 500">模式选择</p>
					<div class="radio">
						<label><input type="radio" name="mode" value="auto" checked="checked">自动模式</input></label>
					</div>
					<div class="radio">
						<label><input type="radio" name="mode" value="manual">手动模式</input></label>
					</div>
					<input type="button" class="btn btn-warning" id="changeMode" value="切换模式" />
				</section>
				<br>
				<br>

				<section>
					<p class="text-warning" style="font-size: 16px; font-weight: 500">棋子选择</p>
					<div class="radio">
					   <label>
					   <input type="radio" name="chess" value="black" checked="checked">执黑棋子</input>
					   </label>
					</div>
					<div class="radio">
					   <label>
					   <input type="radio" name="chess" value="white">执白棋子</input>
					   </label>
					</div>
					<input type="button" class="btn btn-warning" id="changeChess" value="切换棋子" />
				</section>
				<br>

				<section>
					<p><input type="button" class="btn btn-warning" id="goback" value="后退一步" /></p>
					<p><input type="button" class="btn btn-warning" id="goforward" value="前进一步" /></p>
					<p><input type="button" class="btn btn-warning" id="clearChess" value="清空棋子" /></p>
					<br>
				</section>
				<div>
				<section>
					第一步 : <span style="color:green" class="baseChessSpan" id="baseChessSpan">已设置</span>
					<button class="btn btn-warning" id="setBaseChess">设为基础棋局</button>
					<i class="fa fa-question-circle-o" data-toggle="tooltip" style="color:darkorange;" data-placement="right"
					   title="做题前的棋局"></i>

					<input type="text" name="baseChess" id="saveBaseChess" style="display: none" />
					<br>
					第二步 : <span style="color:green" class="answerChessSpan" id="answerChessSpan">已设置</span>
					<button class="btn btn-warning" id="setAnswerChess">设为答案棋局</button>
					<i class="fa fa-question-circle-o" data-toggle="tooltip" style="color:darkorange;" data-placement="right"
					   title="做题后的棋局"></i>
					<input type="text" name="answerChess" id="saveAnswerChess" style="display: none"/>
				</section>
				</div>
				<br>
				<br>
				<section class="ml-20">
					<div class="form-group">
						<label for="courseName">课程名</label>
						<input type="text" class="form-control" name="courseName" id="courseName" placeholder="请填写单节课程名" required>
					</div>
                    <br>
					<div class="form-group">
						<label for="courseName">课程分类</label>
                        <br>
                        <select class="form-control" name="courseLevel" id="courseLevel" style="width: 160px;" required></select>
					</div>
					<p><button type="submit" class="btn btn-success" id="submit">保存课程</button></p>
				</section>
			</aside>
		</div>
	</form>

</article>
	</div>

{/block}


{block name='js'}

<script>
    var xmlns = 'http://www.w3.org/2000/svg',
        xlink = 'http://www.w3.org/1999/xlink';


    $(document).ready(function() {

        var baseChess = "";
        var answerChess = "";

        var chessmen = [],
            backs = [],
            forwards = [],
            index = 0,
            lineCount = 19, //此处可调节棋盘 19*19或者8*8;
            chessboard = document.getElementById('chessboard'),
            length = chessboard.getAttributeNS(null, 'width'),
            centerStar = Math.floor(lineCount / 2),
            leftStar = 3,
            rightStar = lineCount - 4,
            span = length / (lineCount + 1),
            pieceR = span * 0.45,
            starR = span * 0.1,
            hx1 = span,
            hy1 = span,
            hx2 = length - span,
            hy2 = span,
            vx1 = span,
            vy1 = span,
            vx2 = span,
            vy2 = length - span;
        for (var i = 0; i < lineCount; i++) {
            drawLine(chessboard, hx1, hy1, hx2, hy2);
            drawLine(chessboard, vx1, vy1, vx2, vy2);
            hy1 = hy2 += span;
            vx1 = vx2 += span;
        }
        for (var i = 0, hx1 = hy1 = span; i < lineCount; i++) {
            for (var j = 0, x = hx1; j < lineCount; j++) {
                if ((i == leftStar || i == centerStar || i == rightStar) &&
                    (j == leftStar || j == centerStar || j == rightStar)) {
                    drawStar(chessboard, x, hy1, starR);
                }
                drawPiece(chessboard, x, hy1, pieceR);
                x += span;
            }
            hy1 += span;
        }


        function drawLine(parent, x1, y1, x2, y2) {
            var line = document.createElementNS(xmlns, 'line');
            line.setAttribute('x1', x1 - 0.5);
            line.setAttribute('y1', y1 - 0.5);
            line.setAttribute('x2', x2 - 0.5);
            line.setAttribute('y2', y2 - 0.5);
            line.setAttribute('stroke', 'black');
            parent.appendChild(line);
        }

        function drawStar(parent, x, y, r) {
            var circle = document.createElementNS(xmlns, 'circle');
            circle.setAttribute('cx', x - 0.5);
            circle.setAttribute('cy', y - 0.5);
            circle.setAttribute('r', r);
            circle.setAttribute('fill', 'black');
            parent.appendChild(circle);
        }

        // 绘制 下棋的操作
        function drawPiece(parent, x, y, r) {

            var circle = document.createElementNS(xmlns, 'circle');
            circle.setAttribute('cx', x - 0.5);
            circle.setAttribute('cy', y - 0.5);
            circle.setAttribute('r', r);
            circle.index = index++;
            circle.status = function (status) {
                var chess = this;
                return status != null ? (function () {

                    switch (status) {
                        case '1':
                            chess.s = '1';
                            chess.setAttribute('fill', 'url(#rgBlack)');
                            chess.setAttribute('opacity', 1);
                            break;
                        case '2':
                            chess.s = '2';
                            chess.setAttribute('fill', 'url(#rgWhite)');
                            chess.setAttribute('opacity', 1);
                            break;
                        default:
                            chess.s = '0';
                            chess.setAttribute('opacity', 0);
                            break;
                    }
                    return this.s;
                })() : this.s;
            };
            circle.status('0');
            eventHelper.addEvent(circle, 'click', function () {
                var chess = getRadioValueByName('chess'),
                    piece = chess == 'black' ? '1' : '2',
                    tmp = [getStatus(this)],
                    pieces = [];
                if (this.status() == '0') {
                    if (goHelper.hasDeadPieces(this.index, piece == '1' ? '2' : '1', getAllStatus(
                        this.index,
                        piece))) {
                        pieces = goHelper.getDeadPieces();
                        for (var i = 0, tmppiece; i < pieces.length; i++) {
                            tmppiece = chessmen[pieces[i]];
                            tmp.push(getStatus(tmppiece));
                            tmppiece.status('0');
                        }
                    } else if (!goHelper.hasWay(this.index, piece, getAllStatus(this.index, piece),
                        pieces)) {
                        return;
                    }
                    this.status(piece);
                    if (getRadioValueByName('mode') == 'auto') {
                        checkRadioByName('chess', chess == 'black' ? 'white' : 'black');
                    }
                } else {
                    this.status('0');
                }
                backs.push(tmp);
                forwards = [];
            });
            parent.appendChild(circle);
            chessmen.push(circle);
        }

        //模式选择
        eventHelper.addEvent(document.getElementById('changeMode'), 'click', function () {
            checkRadioByName('mode', getRadioValueByName('mode') == 'auto' ? 'manual' : 'auto');
        });
        //棋子选择
        eventHelper.addEvent(document.getElementById('changeChess'), 'click', function () {
            checkRadioByName('chess', getRadioValueByName('chess') == 'black' ? 'white' : 'black');
        });

        //后退一步
        eventHelper.addEvent(document.getElementById('goback'), 'click', function () {
            if (backs.length > 0) {
                var last = backs.pop(),
                    tmp = [];
                for (var i = 0; i < last.length; i++) {
                    tmp.push(getStatus(last[i].piece));
                    last[i].piece.status(last[i].status);
                }
                forwards.push(tmp);
            }
        });

        //前进一步
        eventHelper.addEvent(document.getElementById('goforward'), 'click', function () {
            if (forwards.length > 0) {
                var last = forwards.pop(),
                    tmp = [];
                for (var i = 0; i < last.length; i++) {
                    tmp.push(getStatus(last[i].piece));
                    last[i].piece.status(last[i].status);
                }
                backs.push(tmp);
            }
        });

        //清空棋子
        eventHelper.addEvent(document.getElementById('clearChess'), 'click', function () {
            var piece, tmp = [];
            for (var i = 0; i < chessmen.length; i++) {
                piece = chessmen[i];
                if (piece.status() == '0') continue;
                tmp.push(getStatus(piece));
                piece.status('0');
            }
            if (tmp.length > 0) {
                backs.push(tmp);
                forwards = [];
            }
        });


        //获取当前基础题设棋谱
        eventHelper.addEvent(document.getElementById('setBaseChess'), 'click', function () {
            baseChess = getAllStatus().join('');

            //获取存储基础题设棋谱的element
			var inputElement = document.getElementById("saveBaseChess");
			inputElement.value = baseChess;
            $("#baseChessSpan").removeClass("baseChessSpan");
        });

        //获取当前答案棋谱
        eventHelper.addEvent(document.getElementById('setAnswerChess'), 'click', function () {

            answerChess = getAllStatus().join('');

            if(baseChess === "") {
                layer.open({
                    title: '温馨提示',
                    content: '请先设置基础棋谱作为题设 :('
                });
                return;
            }
            if(baseChess === answerChess) {
                layer.open({
                    title: '温馨提示',
                    content: '题设棋谱和答案棋谱不能相同 :('
                });
                return;
			}

            //获取存储基础题设棋谱的element
            var inputElement = document.getElementById("saveAnswerChess");
            inputElement.value = answerChess;
            console.log(inputElement.value);
            $("#answerChessSpan").removeClass("answerChessSpan");

        });

        //载入棋局
        eventHelper.addEvent(document.getElementById('loadChess'), 'click', function () {
            document.getElementById("browse").click();
        });

        eventHelper.addEvent(document.getElementById('browse'), 'change', function () {
            var file = document.getElementById("browse").files[0];
            fileHelper.upload(file, function (text) {
                var piece, tmp = [];
                for (var i = 0, maxChess = Math.pow(lineCount, 2); i < text.length && i <
                maxChess; i++) {
                    piece = chessmen[i];
                    tmp.push(getStatus(piece));
                    piece.status(text[i]);
                }
                if (tmp.length > 0) {
                    backs.push(tmp);
                    forwards = [];
                }
            });
        });

        function getStatus(piece) {
            return {
                'piece': piece,
                'status': piece.status()
            };
        }

        function getAllStatus(pos, status) {
            var all = [];
            for (var i = 0; i < chessmen.length; i++) {
                all.push(i == pos ? status : chessmen[i].status());
            }
            return all;
        }

        function getRadioValueByName(name) {
            var radios = document.getElementsByName(name);
            for (var i = 0; i < radios.length; i++) {
                if (radios[i].checked) return radios[i].value;
            }
            radios[0].checked = true;
            return radios[0].value;
        }
        function checkRadioByName(name, value) {
            var radios = document.getElementsByName(name);
            for (var i = 0; i < radios.length; i++) {
                if (radios[i].value == value) {
                    radios[i].checked = true;
                    break;
                }
            }
        }

        //前进一步
        eventHelper.addEvent(document.getElementById('setBaseChess'), 'click', function () {
            var baseChess = getAllStatus().join('');
            console.log(baseChess);
            $('#saveBaseChess').val(baseChess);
            $('#baseChessSpan').css("display","inline");
        });

        //课程提交保存
        // eventHelper.addEvent(document.getElementById('submit'), 'click', function () {
        //     alert("fsfsa");

            // $.ajax({
            //     type: "POST",
            //     url: "{:url('course/courseAdd')}",
            //     data: $("#form-student-edit").serialize(),
            //     dataType: "json",
            //     success: function(data){
            //         if (data.status == 1) {
            //             alert(data.message);
            //         } else {
            //             alert(data.message);
            //         }
            //     }
            // });

        // });
    });


    //请求加载课程分类
    (function() {

        $.ajax({
            type: "POST",
            url: "{:url('course/fetchCourseLevelData')}",
            dataType: "json",
            success: function(res){
                if (res.status === 200) {
                    var data = res.data;
                    $("#courseLevel").select2({
                        data: data
                    })
                } else {
                    alert("该练习课程不存在");
                }
            }
        });

    })();




</script>


{/block}

</body>
</html>